/*
 * @Author: xiaorao 2930367909@qq.com
 * @Date: 2024-11-27 14:11:17
 * @LastEditors: xiaorao 2930367909@qq.com
 * @LastEditTime: 2025-02-21 14:39:12
 * @FilePath: \project_management\src\config\reques.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
import storage from "@/utils/storage";
import website from "@/config/website";
import { ElMessage, ElMessageBox } from "element-plus";
import type { Action } from "element-plus";

// 跳出401的名单
const baseURL = website.baseURL;
const axiosConfig = {
  baseURL: baseURL,
  timeout: website.timeout,
};

const service = axios.create(axiosConfig);
axios.defaults.headers["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";

//HTTPRequest拦截器
service.interceptors.request.use(
  async (config) => {
    //设置headers
    let userInfo = storage.getSession("userInfo") || {};
    config.headers["userCode"] = userInfo.userCode || "";

    // 默认参数
    var defaults = {};
    // 防止缓存，GET请求默认带_t参数
    if (config.method === "get") {
      config.params = {
        ...config.params,
        ...{
          _t: new Date().getTime(),
        },
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(new Error(error));
  }
);

//HTTPResponse拦截器
service.interceptors.response.use(
  (res: any) => {
    if (["/system/login"].find((item) => res.config.url.includes(item))) {
      res.data.code = 401;
    }

    const status = res.data.code || 0;
    const message = res.data.err_msg;

    // 默认是显示报错信息
    let isShowMessage = true,
      param = res.config.data;

    try {
      param = JSON.parse(param);
      isShowMessage = param.showMsg != "N";
    } catch (error) {
      isShowMessage = true;
    }

    switch (status) {
      case 1: // 系统异常
        isShowMessage &&
          ElMessageBox.alert(
            message || res.data?.msg || "服务器异常，请稍后重新刷新！",
            "提示",
            {
              // if you want to disable its autofocus
              // autofocus: false,
              confirmButtonText: "OK",
              callback: (action: Action) => {
                ElMessage({
                  type: "info",
                  message: `action: ${action}`,
                });
              },
            }
          );
        return Promise.reject(new Error(message));
      case 2: // 系统异常
        isShowMessage &&
          ElMessageBox.alert(
            message || res.data?.msg || "服务器异常，请稍后重新刷新！",
            "提示",
            {
              // if you want to disable its autofocus
              // autofocus: false,
              confirmButtonText: "OK",
              callback: (action: Action) => {
                ElMessage({
                  type: "info",
                  message: `action: ${action}`,
                });
              },
            }
          );
        return Promise.reject(new Error(message));
      case -1:
        isShowMessage &&
          ElMessageBox.alert(
            message || res.data?.msg || "服务器异常，请稍后重新刷新！",
            "提示",
            {
              confirmButtonText: "OK",
              callback: (action: Action) => {
                ElMessage({
                  type: "info",
                  message: `action: ${action}`,
                });
              },
            }
          );
        return Promise.reject(new Error(message));
    }
    //判断是否文件流
    if (res.config.responseType === "blob") {
      return res;
    } else {
      return res.data;
    }
  },
  (error) => {
    return Promise.reject(new Error(error));
  }
);

export default service;
